package site.mingdao.boot.common.util.locale;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;

@Component
public class LocaleUtils {

    private static MessageSource messageSource;

    public LocaleUtils(MessageSource messageSource) {
        LocaleUtils.messageSource = messageSource;
    }

    /**
     * 获取单个国际化翻译值
     */
    public static String get(String msgKey) {
        return get(msgKey, (Object) null);
    }

    /**
     * 传参获取国际翻译值 语言文件中使用{0} {1} 参数展位
     */
    public static String get(String msgKey, Object... var2) {
        try {
            return messageSource.getMessage(msgKey, var2, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            return msgKey;
        }
    }

    /**
     * 设置语言上下文
     *
     * @param language 语言
     */
    public static void setLocale(String language) {
        String[] s = StringUtils.split(language, "_");
        LocaleContextHolder.setLocale(new Locale(StringUtils.lowerCase(s[0]), StringUtils.upperCase(s[1])));
    }

}